<template>
  <UploadExcel :on-success="handleSuccess" />
</template>

<script>
import { formatExcelDate } from '../../utils/index'
import { importEmployee } from '../../api/employees'
export default {
  name: 'Import',
  methods: {
    async doImport(data) {
      try {
        const res = await importEmployee(data)
        console.log(res)
        this.$message.success('导入成功')
        // 页面后退
        this.$router.back()
      } catch (err) {
        console.log(err)
        this.$message.error('导入失败')
      }
    },
    // 把数据从excel文件读入到浏览器内存
    handleSuccess({ header, results }) {
      console.log(header, results)
      const data = this.transExcel(results)
      console.log('组装的数据', data)
      // 调用接口做上传
      this.doImport(data)
    },
    // 把数组中每个对象的属性名，改成英文
    transExcel(results) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }

      const arr = results.map(zwobj => {
        const ywobj = {}
        // 找到所有中文key
        const zwKeys = Object.keys(zwobj)

        zwKeys.forEach(zwKeys => {
          // 遍历中文key映射成英文key
          const ywkeys = mapInfo[zwKeys]
          if (ywkeys === 'timeOfEntry' || ywkeys === 'correctionTime') {
            // 后端需要的日期格式是标准时间
            ywobj[ywkeys] = new Date(formatExcelDate(zwobj[zwKeys]))
          } else {
            ywobj[ywkeys] = zwobj[zwKeys]
          }
        })
        return ywobj
      })
      return arr
    }
  }
}
</script>
